<!DOCTYPE html>
<html>

<head>
  <title>Photo Wall</title>
  <meta charset='utf-8' />
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    #container > img,
    #container > div {
      position: absolute;
      /*margin:0 1px 1px 0;border-right:1px solid #fff;border-bottom:1px solid #fff;*/
    }

    #container > div {
      overflow: hidden;
    }

    #container > div > img {
      display: block;
      position: absolute;
      left: 50%;
      top: 50%;
      max-width: 128px;
      max-height: 192px;
      width: 100%;
      -webkit-transform: translate(-50%, -50%);
      -moz-transform: translate(-50%, -50%);
      transform: translate(-50%, -50%);
    }

    body {
      /*background: #fce6cf;*/
      background: #000;
    }

    .outer {
      width: 768px;
      height: 768px;
      overflow: hidden;
      position: relative;
      margin-left: auto;
      margin-right: auto;
    }
  </style>
</head>

<body>
  <div id="container" class="outer"></div>
  <script src="/vendor/mootools/dist/mootools-core.min.js"></script>
  <script type="text/javascript">
    (function () {
      'use strict';

      function getUrlParams() {
        var params = {};
        var url = window.location.href;
        var idx = url.indexOf('?');
        if (idx > 0) {
          var queryStr = url.substring(idx + 1);
          var args = queryStr.split('&');
          for (var i = 0, a, nv; a = args[i]; i++) {
            nv = args[i] = a.split('=');
            params[nv[0]] = nv.length > 1 ? nv[1] : true;
          }
        }
        return params;
      }

      var prefix = '/assets/<%= eventId %>/',
        ops = {
          iniW: 350,
          iniH: 350,
          width: 128,   // image width
          height: 192,  // image height
          ctnW: 768,   // container width
          ctnH: 768,   // container height
          maxN: 18,     // the max display number of photos. Must be smaller than the total number of slots on the screen
          logoNum: 0
        },
        flag = {
          request: true,
          counter: 0
        }, //guid the Ajax request
        ctn = $('container');

      // PRELOAD LOGOS
      var logos = [];
      ['/images/pw/2015027/logo.jpg'].each(function (path) {
        var image = new Element('img');
        image.onload = function () {
          logos.push(this);
        };
        image.set({
          src: path,
          name: 'logo'
        });
      });
      // END OF PRELOADING LOGOS

      var params = getUrlParams();
      var c_event_id = <%= eventId %> || 0,
        last_time = 0;
      ops.maxN = params.maxN || ops.maxN;


      var ImageManager = function () {
        var imgArray = [];
        var imgs = this.imgs = [];

        this.reset = function (arr) {
          if (arr.length > 0) {
            if (flag.request == true) flag.request = false;
            imgArray = arr;
            load();
          }
        };

        this.getFirst = function () {
          var rand = Number.random(0, 2);
          if (logos.length === 0 && imgs.length === 0) {
            flag.request = true;
            return false;
          }
          if (logos.length > 0 && imgs.length > 0) {
            return rand === 0 ? logos.shift() : imgs.shift();
          }
          if (logos.length === 0 && imgs.length > 0) {
            return imgs.shift();
          }
          if (logos.length > 0 && imgs.length === 0) {
            return logos.shift();
          }
        };

        this.log = function () {
          console.log(imgs.length);
        };

        function load() {
          last_time = imgArray.getLast()['timestamp'];
          imgArray.each(function (imgArr, key) {
            var div = new Element('div');

            var img = new Element('img');
            img.set({
              src: prefix + imgArr['filename'].replace(/(\.jpe?g)$/, "_s$1")
            });
            img.store('parent', div);
            div.set({
              time: imgArr['timestamp'],
              name: imgArr['photo_id']
            });
            img.addEvent('load', function () {
              imgs.push(this.retrieve('parent'));
              this.removeEvent('load');
            })
            div.grab(img);
          });
        }
      };

      var im = new ImageManager();
      var requestSignatures = new Request({
        url: '/photolist/' + c_event_id,
        method: 'get',
        link: 'ignore',
        timeout: 5000,
        noCache: true,
        onSuccess: function (obj) {
          //rawList = JSON.decode(obj);
          var o = JSON.decode(obj);
          if (typeOf(o) == 'array' && o.length > 0) {
            im.reset(o);
            if (flag.request == true) flag.request = false;
          }
        }
      });

      var LocationManager = function () {
        var totalWidth = ops.ctnW,
          totalHeight = ops.ctnH,
          indivalWidth = ops.width,
          indivalHeight = ops.height,

          cols = parseInt(totalWidth / indivalWidth),
          rows = parseInt(totalHeight / indivalHeight),
          offX = parseInt((totalWidth % indivalWidth) / 2),
          offY = parseInt((totalHeight % indivalHeight) / 2);
        var locations = this.locations = [];
        for (var i = 0; i < rows; i++) {
          for (var j = 0; j < cols; j++) {
            locations.push({
              'left': offX + indivalWidth * j,
              'top': offY + indivalHeight * i,
              'id': i + '' + j,
              'ocupied': false
            });
          }
        }
        this.log = function () {
          console.log(totalWidth);
          console.log(totalHeight);
          console.log(indivalWidth);
          console.log(indivalHeight);
          console.log(cols + '*' + rows);
          console.log(offX);
          console.log(offY);
          console.log(locations);
        };
        this.dim = function () {
          return {
            'width': indivalWidth,
            'height': indivalHeight
          };
        };
        this.getUnocupied = function () {
          //var length = locations.length;
          if (locations.every(function (location) {
              return location.ocupied == true;
            })) {
            return false;
          }
          var r = {};
          do {
            r = locations.getRandom();
          } while (r.ocupied);
          return r;
        };
        this.getOcupied = function () {
          if (locations.every(function (location) {
              return location.ocupied == false;
            })) return false;
          var r = {};
          do {
            r = locations.getRandom();
          } while (!r.ocupied);
          return r;
        };
        this.getONum = function () {
          // var num = 0;
          // locations.each(function(location) {
          // 	if (location.ocupied == true)
          // 		num++;
          // });
          return locations.filter(function(location){
            return location.ocupied;
          }).length;
          /*
          return _.filter(locations, function (location) {
            return location.ocupied;
          }).length;
          */
          // return num;
        };
        this.clean = function (str) {
          locations.each(function (location) {
            if (location.id == str)
              location.ocupied = false;
          })
        };
      }
      var myLM = new LocationManager();
      var dim = myLM.dim();

      /*
        	coor = myLM.locations.splice(1,5)[0];

        	var logo06 = new Element('img',{
        		class:'animated',
        		src:'images/bayer/bayer.png',
        		width:(dim.width+1)*5,
        		height:dim.height,
        		styles:{
        			left:coor.left + 'px',
        			top:coor.top  + 'px',
        			opacity:0
        		}
        	});
        	ctn.grab(logo06);
        	*/
      /*
        	coor = myLM.locations.splice(6,1)[0];
        	var topLogo = new Element('img',{
        		src:'images/fwlogo_01.png',
        		width:dim.width,
        		height:dim.height,
        		styles:{
        			left:coor.left + 'px',
        			top:coor.top  + 'px'
        		}
        	});
        	ctn.grab(topLogo);
        	?action=list_photo_wall&c_event_id=1124&r_datetime=0&num=25
        	*/
      requestSignatures.send('startTime=' + last_time);

      var iniLeft = (ops.ctnW - ops.iniW) / 2,
        iniTop = (ops.ctnH - ops.iniW) / 2;

      function pulse() {
        setTimeout(pulse, '2000');
        if (flag.counter == 2) {
          flag.counter = 0;
          var decache = Math.random();
          if (flag.request == true) {
            requestSignatures.send('startTime=' + last_time);
          }
        }
        flag.counter++;

        if (myLM.getONum() <= ops.maxN) {

          $$('.dispose').each(function (el) {
            el.destroy();
          });
          var newImg = im.getFirst();

          if (newImg) {
            //add new photos
            newImg.setStyles({
              'width': ops.width + 'px',
              'height': ops.height + 'px',
              'opacity': '0',
            });

            ctn.grab(newImg);
            var effect_1 = new Fx.Morph(newImg, {
              duration: 900,
              transition: Fx.Transitions.Sine.easeOut,
              link: 'chain'
            });
            var coor = myLM.getUnocupied();
            if (coor) {
              coor.ocupied = true;
              newImg.set('num', coor.id);
              newImg.setStyles({
                'left': coor.left + 'px',
                'top': coor.top + 'px'
              });
              effect_1.start({
                'opacity': '1'
              });
            }

          } else {
            $$('.dispose').each(function (el) {
              el.destroy();
            });

            if (ctn.children.length > 0) {
              var el_1_idx = Number.random(ops.logoNum, ctn.children.length - 1);
              var el_1 = ctn.children[el_1_idx];

              var newCoor = myLM.getUnocupied();
              var oldNumber = el_1.get('num');
              myLM.clean(oldNumber);
              var el_2 = el_1.clone();
              if (newCoor) {
                newCoor.ocupied = true;
                el_2.set('num', newCoor.id);
                el_2.setStyles({
                  'left': newCoor.left + 'px',
                  'top': newCoor.top + 'px',
                  'opacity': '0'
                });
                ctn.grab(el_2);
                el_1.set('class', 'dispose');
                var effect_el_1 = new Fx.Morph(el_1, {
                  duration: 900,
                  transition: Fx.Transitions.linear,
                  link: 'chain'
                });
                effect_el_1.start({
                  'opacity': '0'
                });

                var effect_el_2 = new Fx.Morph(el_2, {
                  duration: 900,
                  transition: Fx.Transitions.linear,
                  link: 'chain'
                });
                effect_el_2.start({
                  'opacity': '1'
                });
              }
            }
          }
        } else {
          $$('.dispose').each(function (el) {
            el.destroy();
          });
          var outNumber = notLogo();

          var outImg = ctn.children[outNumber];
          var roomNum = outImg.get('num');
          myLM.clean(roomNum);
          outImg.set('class', 'dispose');
          var effect_outImg = new Fx.Tween(outImg, {
            duration: 1200,
            transition: Fx.Transitions.linear,
            link: 'chain'
          });
          effect_outImg.start('opacity', '0');

          var nextImg = im.getFirst();
          if (nextImg) {
            //add new photoes

            nextImg.setStyles({
              width: ops.width + 'px',
              height: ops.height + 'px',
              opacity: '0'
            });
            ctn.grab(nextImg);
            var effect_nextImg = new Fx.Morph(nextImg, {
              duration: 1200,
              transition: Fx.Transitions.Sine.easeOut,
              link: 'chain'
            });
            var nextCoor = myLM.getUnocupied();
            if (nextCoor) {
              nextCoor.ocupied = true;
              nextImg.set('num', nextCoor.id);
              nextImg.setStyles({
                left: nextCoor.left,
                top: nextCoor.top
              });
              effect_nextImg.start({
                'opacity': '1'
              });

            }
          }
        }

        function notLogo() {
          var type = '',
            num;
          do {
            num = Number.random(ops.logoNum, ctn.children.length - 1);
            type = ctn.children[num].get('name');
          } while (type == 'logo')
          return num;
        }
      }
      pulse();
    })();
  </script>
</body>

</html>
